from forest.server.api.basehandler import BaseHandler
from forest.server.models.node import Node
from forest.server.forms.node import NodeForm
import os
import os
from xml.sax.saxutils import quoteattr as xml_quoteattr

def DirAsLessXML(rootpath):
    result = '<div class="directory">%s\n' % os.path.basename(rootpath)
    for item in os.listdir(rootpath):
        itempath = os.path.join(rootpath, item)
        if os.path.isdir(itempath):
            result += '\n'.join('  ' + line for line in
                DirAsLessXML(os.path.join(rootpath, item)).split('\n'))
        elif os.path.isfile(itempath) and itempath.endswith('tree'):
            result += '  <div class="file">%s</div>\n' % (itempath.replace(rootpath ,''))
    result += '</div>'
    # xml_quoteattr

    result = ""
    for (path, dirs, files) in os.walk(rootpath):
        print path
        print dirs
        print files
        for file in files:
            if not file.endswith('tree'):
                continue
            result+='<div>%s</div>' % (path.replace(rootpath,'')+'/'+file)

    return result

class ShowRoot(BaseHandler):
    def get(self):
        self.data['dump'] =  DirAsLessXML(self.app.config.get('forest_root'))
        return self.render_template('templates/showroot.html')
